import markdownStyle from './markdown.module.less';
import {useEffect, useRef, useState} from "react";
import md from "./markdown.js";
import { importMarkdown, markdownContent} from "../uitls/uitls.js";

let scrolling = 0  // 0: none; 1: 编辑区主动触发滚动; 2: 展示区主动触发滚动
let scrollTimer;  // 结束滚动的定时器
export default function Markdown() {
    const [contentHtml, setContentHtml] = useState('') // 展示区的文字内容
    const [value, setValue] = useState('')   // 编辑区的文字内容
    const editRef = useRef(null)  // 编辑区元素
    const showRef = useRef(null)  // 展示区元素
    const handleScroll = (block, event) => {
        let {scrollHeight, scrollTop, clientHeight} = event.target
        let scale = scrollTop / (scrollHeight - clientHeight)
        if (block === 1) {
            if (scrolling === 0) scrolling = 1;  // 记录主动触发滚动的区域
            if (scrolling === 2) return;    // 当前是「展示区」主动触发的滚动，因此不需要再驱动展示区去滚动
            driveScroll(scale, showRef.current)  // 驱动「展示区」的滚动
        } else if (block === 2) {
            if (scrolling === 0) scrolling = 2;
            if (scrolling === 1) return;    // 当前是「编辑区」主动触发的滚动，因此不需要再驱动编辑区去滚动
            driveScroll(scale, editRef.current)
        }
    }
    // 驱动一个元素进行滚动
    const driveScroll = (scale, el) => {
        let {scrollHeight} = el
        el.scrollTop = scrollHeight * scale
        if (scrollTimer) clearTimeout(scrollTimer);
        scrollTimer = setTimeout(() => {
            scrolling = 0    // 在滚动结束后，将scrolling设为0，表示滚动结束
            clearTimeout(scrollTimer)
        }, 200)
    }
    const addBasic = (symbol, operation) => {
        let { selectionStart, selectionEnd } = editRef.current
        const start = selectionStart
        const end = selectionEnd
        let newValue = selectionStart === selectionEnd
            ? value.slice(0, start) + `${symbol}${operation}${symbol}` + value.slice(end)
            : value.slice(0, start) + symbol + value.slice(start, end) + symbol + value.slice(end)
        setValue(newValue)
    }
    const addImg = () =>{
        console.log('插入图片')
    }
    useEffect(() => {
        // 编辑区内容改变，更新value的值，并同步渲染
        setContentHtml(md.render(value))
    }, [value])
    return (
        <div className={`${markdownStyle.markdownContent}`}>
            <div className={markdownStyle.markdownTitleTool}>
                <button className='mr8' onClick={() => addBasic('**','加粗')}>加粗</button>
                <button className='mr8' onClick={() => addBasic('_','倾斜')}>倾斜</button>
                <button className='mr8' onClick={() => addBasic('~~','删除线')}>删除线</button>
                <button className='mr8' onClick={() => addBasic('---','')}>分割线</button>
                <button className='mr8' onClick={() => addImg()}>插入图片</button>
                <button className='mr8' onClick={() => markdownContent(value)}>导出md</button>
                <button className='mr8' onClick={() => importMarkdown(setValue)}>导入md</button>
            </div>
            <div className={`${markdownStyle.markdownMiddle} flex`}>
                <textarea
                    className={`${markdownStyle.markdownLeft} pl8 pt8 pr8`}
                    ref={editRef}
                    onScroll={(e) => handleScroll(1, e)}
                    onChange={(e) => setValue(e.target.value)}
                    value={value}/>
                <div
                    id="write"
                    ref={showRef}
                    className={`${markdownStyle.markdownRight} pl20 pt8`}
                    onScroll={(e) => handleScroll(2, e)}
                    dangerouslySetInnerHTML={{__html: contentHtml}}/>
            </div>
        </div>
    )
}
